package me.sealer.ssm.service.impl;

import lombok.extern.slf4j.Slf4j;
import me.sealer.ssm.constant.DwzConstant;
import me.sealer.ssm.mapper.DwzMapper;
import me.sealer.ssm.model.Dwz;
import me.sealer.ssm.model.DwzExample;
import me.sealer.ssm.service.DwzService;
import me.sealer.ssm.utils.UrlUtil;
import org.apache.shiro.util.Assert;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 功能描述： $ DwzServiceImpl
 *
 * @author sealer
 * @email 1178884049@qq.com
 * @date 2020年01月15日 10时57分15秒
 */
@Slf4j
@Service
public class DwzServiceImpl implements DwzService {
    private final DwzMapper dwzMapper;

    public DwzServiceImpl(DwzMapper dwzMapper) {
        this.dwzMapper = dwzMapper;
    }

    @Override
    public Dwz queryByShortUrl(String shortUrl) {
        DwzExample dwzExample = new DwzExample();
        dwzExample.createCriteria().andShortUrlEqualTo(shortUrl);
        List<Dwz> dwzList = dwzMapper.selectByExample(dwzExample);
        // lsl dwzList长度必须为1
        Assert.isTrue(dwzList.size() == 1, "脏数据异常");
        return dwzList.get(0);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String generateShortUrl(String dwzPrefix, String longUrl) {
        //如果长地址不是以http开头， 则添加默认协议 http:// 注意：https亦是http开头。
        if (!longUrl.startsWith(DwzConstant.HTTP)) {
            longUrl = "http://" + longUrl;
        }

        DwzExample dwzQueryExample = new DwzExample();
        dwzQueryExample.createCriteria().andLongUrlEqualTo(longUrl);
        List<Dwz> dwzList = dwzMapper.selectByExample(dwzQueryExample);
        // 已存在， 直接返回
        if (dwzList.size() > 0) {
            // 有且只能有一条记录
            Assert.isTrue(dwzList.size() == 1, "脏数据异常");
            // 计数器加1
            dwzMapper.updateByPrimaryKeySelective(Dwz.builder().id(dwzList.get(0).getId()).longNum(dwzList.get(0).getLongNum() + 1).build());
            return UrlUtil.assembleUrl(dwzPrefix, dwzList.get(0).getShortUrl());
        }

        //将长URL插入数据库（主键id自增）
        dwzMapper.insertSelective(Dwz.builder().longUrl(longUrl).build());

        //拿到刚插入的记录的ID， 用作生成短URL
        dwzList = dwzMapper.selectByExample(dwzQueryExample);

        // lsl dwzList 不为空且长度必须为1
        Assert.isTrue(dwzList.size() == 1, "脏数据异常");

        Dwz dwz = dwzList.get(0);

        //生成短URL
        String shortUrl = UrlUtil.genShortUrl(dwz.getId(), 6);

        //将生成的短URL更新到数据库
        dwzMapper.updateByPrimaryKeySelective(Dwz.builder().id(dwz.getId()).shortUrl(shortUrl).build());

        return UrlUtil.assembleUrl(dwzPrefix, shortUrl);
    }
}
